<?php

namespace App\Http\Controllers\functions;

use Illuminate\Http\Request;
use App\Models\CustomMenu;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class CustomMenuController extends Controller
{
    protected $name = '自定义菜单';
    //查询列表字段
    protected $findlist = ['id', 'MenuName', 'userid', 'roleid', 'des', 'state', 'tabnm', 'modifier', 'updated_at', 'created_at'];
    //查询详情字段
    protected $fielddetail = ['id', 'MenuName', 'userid', 'roleid', 'des', 'state', 'tabnm', 'modifier', 'updated_at', 'created_at', 'datatext'];


    //首页获取菜单
    public function LoadMenu(Request $request)
    {
        try {
            $usr = $this->decodetoken();
            //先取用户菜单
            $res = DB::table('custommenu')
                ->select($this->fielddetail)
                ->whereRaw('isdel=0 and state=1 and userid=' . $usr->userid)
                ->get();
            //没有的话，再先取用户角色菜单    
            if ($res->isEmpty()) {
                $role = DB::table('userrole')
                    ->join('UsrGroup', 'userrole.roleid', '=', 'UsrGroup.id')
                    ->select(['userrole.id', 'UsrGroup.id as roleid0', 'userrole.userid', 'UsrGroup.des', 'UsrGroup.usrgroupid as roleid', 'UsrGroup.name as rolenm', 'userrole.isdel'])
                    ->whereRaw(" userrole.userid=" . $usr->id . " and userrole.isdel=0 and UsrGroup.isdel=0")->get();
                if (!$role->isEmpty()) {
                    $rolearr = [];
                    foreach ($role as $key) {
                        $rolearr[] = $key->roleid0;
                    }
                    $res = DB::table('custommenu')
                    ->select($this->fielddetail)
                    ->whereRaw('isdel=0 and state=1 and userid is null and id<>1 and roleid in ('.implode(',',$rolearr).')' )
                    ->get();
                }
            }
            //再没有，就获取全局菜单
            if ($res->isEmpty()) {
                $res = DB::table('custommenu')
                    ->select($this->fielddetail)
                    ->whereRaw('isdel=0 and state=1 and userid is null and roleid is null and id<>1')
                    ->get();
            }
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }
    //查询列表
    public function findlist(Request $request)
    {
        try {
            $temp = $this->findlistdata($request);
            $res = $temp['data'];
            $allcount = $temp['total'];
            $this->log(['operator' => null, 'type' => '查看', 'billcaption' => '菜单管理', 'des' => '操作人[查看]了菜单管理']);
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'count' => $allcount, 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }

    //查询详情
    public function finddetail(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            if (!$id) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|ID不能为空!']);
            }
            $where = ' id=' . $id;
            $res = DB::table('custommenu as a')
                ->select($this->fielddetail)
                ->whereRaw($where)
                ->get();
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }

    //保存
    public function save(Request $request)
    {
        try {
            $usr = $this->decodetoken();
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            $MenuName = $this->I($param['MenuName'] ?? null);
            $userid = $this->I($param['userid'] ?? null);
            $roleid = $this->I($param['roleid'] ?? null);
            $des = $this->I($param['des'] ?? null);
            $state = $this->I($param['state'] ?? null);
            $tablist = $this->I($param['tablist'] ?? null);
            if (empty($MenuName)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '保存失败,方案名称不能为空!']);
            }
            if (empty($tablist)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '保存失败,数据不能为空!']);
            }
            $list = [
                'MenuName' => $MenuName,
                'state' => $state,
                'userid' => $userid,
                'roleid' => $roleid,
                'des' => $des,
                'modifier' => $usr->name,
                'datatext' => json_encode($tablist)
            ];
            $type = '';
            //新增
            if (empty($id)) {
                $type = '新增';
                $list['tabnm'] = $usr->name;
                $res = CustomMenu::create($list);
                if ($res) {
                    $id = $res->id;
                } else {
                    return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|新增失败!', 'id' => null]);
                }
            } else {//修改
                $type = '修改';
                $uptab = CustomMenu::find($id);
                $uptab->update($list);
                $res = $uptab;
            }
            //如果启用,其它对应类型的菜单自动关闭启用
            //用户优先级最高,其次角色,最后全局,如果同时设置了用户和角色,那么只启用用户
            if ($state == 1) {
                if (!empty($userid)) {
                    DB::table('CustomMenu')
                        ->where('id', '<>', $id)
                        ->where('userid', '=', $userid)
                        ->update(['state' => 0]);
                } else if (!empty($roleid)) {
                    DB::table('CustomMenu')
                        ->where('id', '<>', $id)
                        ->where('roleid', '=', $roleid)
                        ->where('userid', '=', null)
                        ->update(['state' => 0]);
                } else {
                    DB::table('CustomMenu')
                        ->where('id', '<>', $id)
                        ->where('roleid', '=', null)
                        ->where('userid', '=', null)
                        ->update(['state' => 0]);
                }
            } else {
                //如果禁用了全局类型，默认菜单则启用
                if (empty($userid) && empty($roleid)) {
                    DB::table('CustomMenu')
                        ->where('id', '=', 1)
                        ->update(['state' => 1]);
                }
            }
            //记录日志
            $this->log(['operator' => $usr->name, 'type' => $type, 'billcaption' => '菜单管理', 'des' => '操作人[' . $type . ']了菜单|[' . $MenuName . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|保存成功!', 'id' => $id]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|保存失败!','error'=>$e->getMessage()]);
        }
    }

    //启用
    public function enablehandle(Request $request)
    {
        try {
            $usr = $this->decodetoken();
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            $name = $this->I($param['name'] ?? null);
            $page = intval($this->I(param: $param['page'] ?? 1));
            $pagecount = intval($this->I($param['pagecount'] ?? 10));

            //$state = $this->I($param['state'] ?? null);
            $type = '启用';
            $uptab = CustomMenu::find($id);
            $uptab->update(['state' => 1]);
            $res = $uptab;
            //如果启用,其它对应类型的菜单自动关闭启用
            //用户优先级最高,其次角色,最后全局,如果同时设置了用户和角色,那么只启用用户
            if (!empty($uptab->userid)) {
                DB::table('CustomMenu')
                    ->where('id', '<>', $id)
                    ->where('userid', '=', $uptab->userid)
                    ->update(['state' => 0]);
            } else if (!empty($uptab->roleid)) {
                DB::table('CustomMenu')
                    ->where('id', '<>', $id)
                    ->where('roleid', '=', $uptab->roleid)
                    ->where('userid', '=', null)
                    ->update(['state' => 0]);
            } else {
                DB::table('CustomMenu')
                    ->where('id', '<>', $id)
                    ->where('roleid', '=', null)
                    ->where('userid', '=', null)
                    ->update(['state' => 0]);
            }

            //记录日志
            $this->log(['operator' => $usr->name, 'type' => $type, 'billcaption' => '菜单管理', 'des' => '操作人[启用]了菜单|[' . $uptab->MenuName . ']']);
            //操作完成后查询当前条件下的数据
            $temp = $this->findlistdata($request);
            $res = $temp['data'];
            $allcount = $temp['total'];
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|操作成功!页面刷新后配置生效!', 'count' => $allcount, 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|操作失败!','error'=>$e->getMessage()]);
        }
    }

    //删除
    public function delete(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            if (!$id) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . 'ID不能为空']);
            }
            $uptab = CustomMenu::find($id);
            $uptab->update(['isdel' => 1]);
            //记录日志
            $this->log(['operator' => null, 'type' => '删除', 'billcaption' => '菜单管理', 'des' => '操作人[删除]了菜单[' . $uptab->MenuName . ']']);
            //操作完成后查询当前条件下的数据
            $temp = $this->findlistdata($request);
            $res = $temp['data'];
            $allcount = $temp['total'];
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|删除成功!', 'count' => $allcount, 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|删除失败!','error'=>$e->getMessage()]);
        }
    }

    protected function findlistdata(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $MenuName = $this->I($param['MenuName'] ?? null);
            $page = intval($this->I(param: $param['page'] ?? 1));
            $pagecount = intval($this->I($param['pagecount'] ?? 10));
            $where = ' isdel=0';
            if (!empty($MenuName)) {
                $where .= " and menuname = '$MenuName' ";
            }
            $temp = DB::table('custommenu as a')
                ->select($this->findlist)
                ->whereRaw($where)
                ->paginate($pagecount, ['id'], 'page', $page)
                ->toArray();
            return $temp;
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }
}
